﻿using System;
using System.Configuration;
using Aurora.DataAccess;
using Aurora.Infrastructure;
using ComponentFactory.Krypton.Toolkit;

namespace Aurora.Core.ViewForms
{
    public partial class frmConnect : KryptonForm
    {
        private readonly DbSelector _dbSelector;

        public frmConnect()
        {
            InitializeComponent();
            _dbSelector = new DbSelector();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            SetConnection();
        }

        private void SetConnection()
        {
            if (tbConnectSourceAddress.Text.Length < 1 || tbConnectSourceLogin.Text.Length < 1 || tbConnectSourcePass.Text.Length < 1)
            {
                Messenger.ShowErrorMessage("Некорректные данные", "Проверьте правильность ввода данных");
            }

            string connStr;
            string providerName;

            switch (cmbConnectSource.SelectedIndex)
            {
                case 0:
                    {
                        connStr = _dbSelector.GetMySqlConnStr(tbConnectSourceAddress.Text, tbConnectSourceLogin.Text,
                                                                tbConnectSourcePass.Text);
                        providerName = _dbSelector.GetMySqlProvName();
                        break;
                    }
                case 1:
                    {
                        connStr = _dbSelector.GetMsSqlConnStr(tbConnectSourceAddress.Text, tbConnectSourceLogin.Text,
                                                                tbConnectSourcePass.Text);
                        providerName = _dbSelector.GetMsSqlProvName();
                        break;
                    }
                default:
                    {
                        return;
                    }
            }

            _dbSelector.CheckConnection(providerName, connStr);

            if(!ChangeConnectionString(connStr, providerName))
                Messenger.ShowErrorMessage("Configuration section error", "Не удается изменить строку подключения");
            

            Close();
        }

        private void btnConnectCE_Click(object sender, EventArgs e)
        {
            if (!ChangeConnectionString(_dbSelector.GetSqlCeConnStr(),  _dbSelector.GetSqlCeProvName()))
                Messenger.ShowErrorMessage("Configuration section error", "Не удается изменить строку подключения");
            
            Close();
        }

        /// <summary>
        /// Хак, позволяющий изменить строку подключения в конфигурационном файле.
        /// </summary>
        /// <param name="connectionString">Строка подключения</param>
        /// <param name="providerName">Провайдер подключения</param>
        /// <returns>bool</returns>
        private bool ChangeConnectionString(string connectionString, string providerName)
        {
            try
            {
                var fileMap = new ExeConfigurationFileMap
                                  {
                                      ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + @"Aurora.Core.exe.config"
                                  };
                var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

                config.ConnectionStrings.ConnectionStrings["AuroraEntities"].ConnectionString = connectionString;
                config.ConnectionStrings.ConnectionStrings["AuroraEntities"].ProviderName = providerName;
                config.Save();

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
    